package iniTable

import (
	"bufio"
	. "git.oschina.net/yangdao/extlib/data_type"
	"io"
	"os"
	"regexp"
	"strings"
)

func LoadiniTableByPath(tablePath string) (error, IAssociative) {
	file, err := os.Open(tablePath)
	if err != nil {
		return err, nil
	}
	return nil, LoadiniTableByReader(file)
}

func LoadiniTableByReader(reader io.Reader) IAssociative {
	RetMap := HashMap()
	re := regexp.MustCompile(`[\t ]*([0-9A-Za-z_]+)[\t ]*=[\t ]*([^\t\n\f\r# ]+)[\t #]*`)
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanLines)

	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		// expression match
		slice := re.FindStringSubmatch(line)
		if slice != nil {
			RetMap.Assoc(slice[1], slice[2])
		}
	}
	return RetMap
}
